package com.ice.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.ice.entity.ReceiveXmlEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ice.common.IceConstants;
import com.ice.common.IceLog;
import com.ice.common.IceProperties;
import com.ice.service.UserService;
import com.ice.service.WeChatFunctionService;
import com.ice.service.WeChatService;
import com.ice.service.impl.WeChatServiceImpl;
import com.ice.tools.GenerateResponseXml;



/**
 * 
 * @author gangchaopan
 * @function 测试程序
 * @time  2016-10-27
 */
@Controller
public class TestController {
	
   @Autowired
   private WeChatService wxService;
  
   @Autowired
   private WeChatFunctionService weChatFunctionService;
   
   Logger log = LoggerFactory.getLogger(TestController.class);
	
	@RequestMapping(value="/test")
	@ResponseBody
	public Map<String, Object> sayHello(HttpServletRequest request,HttpServletResponse response){
		long startTime = System.currentTimeMillis();
		Map<String, Object> map  = new HashMap<String, Object>();
	
		map.put("time", System.currentTimeMillis());
		map.put("user", "test");
	
		log.debug("{}",IceLog.printLog(startTime, "测试系统是否可用", "系统正常运行"));
		return map;
	}
	
	/**
	 
     * @return
	 */
	@RequestMapping(value="link",method = RequestMethod.GET)
	@ResponseBody
	public String linkWeinXin(HttpServletRequest request, HttpServletResponse response){
        long startTime = System.currentTimeMillis();
		String echostr     = request.getParameter("echostr");
        
		if(echostr!=null|| echostr.length()>0){//第一次接入是有echostr，验证成功后就没有了
			//该token是人工设置的，该参数放到文件中，和在微信人工设置的一致。
			String token=IceProperties.getValue(IceConstants.WECHAT_PROPERTIES_URI,IceConstants.WECHAT_TOKEN);
			
			//获取微信传过来的参数timestamp nonce echostr signature
			String timestamp   = request.getParameter("timestamp");
			String nonce       = request.getParameter("nonce");
			String signature   = request.getParameter("signature");
			ArrayList<String> parameters  = new ArrayList<String>();
			parameters.add(token);
	        parameters.add(timestamp);
	        parameters.add(nonce);
	    	log.debug("传递的参数大小:{}",parameters.size());
	        boolean checksignature = wxService.checkSignature(parameters,signature);
	        
	        if(checksignature){
	        	//原样返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败。
	        	log.debug("{}",IceLog.printLog(startTime, "接入微信服务器", "接入微信服务器成功"));
	        	return 	echostr;
	        }
	       log.debug("{}",IceLog.printLog(startTime, "接入微信服务器", "接入微信服务器失败"));
	       return null;
	       
		}else{
			//默认
			log.debug("{}",IceLog.printLog(startTime, "测试系统是否需要校验", "系统不需要再次校验"));
			return null;
		}
		
	}
	
	
	@RequestMapping(value="/link",method = RequestMethod.POST,produces={"application/xml;charset=utf-8"})
	@ResponseBody
	public  String processWeChatTest(HttpServletRequest request,HttpServletRequest response){
		long startTime = System.currentTimeMillis();
		InputStream inputStream;
		try {
			inputStream = request.getInputStream();
		
		 InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");  
		 BufferedReader br = new BufferedReader(isr); 
		 StringBuilder sb = new StringBuilder();
	        String s = "";  
	        while ((s = br.readLine()) != null) {  
	            sb.append(s);  
	        }  
	        String xml = sb.toString(); //次即为接收到微信端发送过来的xml数据  
	       ReceiveXmlEntity entity = wxService.processWeChatMessage(xml);
	       
	        
	        if(entity.getContent().equals("报名")){
	        	String responseXml=weChatFunctionService.responseTextEnroll(entity);
	        	log.debug("{}",IceLog.printLog(startTime, "获取客户发送信息", responseXml));
	        	return new String(responseXml.getBytes(),"utf-8");	
	        }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	
	
	
}
